<template>
  <div class="profile-content-item profile-basic-data">
    <div class="avatar">
      <n-avatar round :size="100" :src="avatar ? `${VUE_APP_BASE_URL}${avatar}` : avatarImg" />
      <!-- <n-upload
        accept="image/*"
        :show-file-list="false"
        :action="`${VUE_APP_BASE_URL}/crm/common/upload`"
        :headers="headers"
        @finish="handleFinish"
      >
        <n-button type="primary" text>{{ $t('profile.form.updateAvatar') }}</n-button>
      </n-upload> -->
    </div>
    <DFForm
      class="basicForm"
      :getLabelFrom="'table'"
      labelPlacement="left"
      require-mark-placement="left"
      :labelWidth="120"
      @register="basicDataFormRegister"
    />
    <n-button
      class="save-button"
      type="primary"
      :disabled="buttonDisabled"
      :loading="loading"
      @click="handleSaveProfileFn"
    >
      {{ t('common.button.save') }}
    </n-button>
  </div>
</template>

<script lang="ts" setup name="Profile">
  import { ref } from 'vue';
  import { DFForm, FormSchema, useForm } from '@/components/DFForm/index';
  // import { useMessage } from 'naive-ui';
  import { useMixins } from '@/hooks/useMixins';
  // import { useUserStoreWidthOut } from '@/store/modules/user';
  // import { updateUserCenter } from '@/api/system/user';
  import { cloneDeep } from 'lodash-es';
  import lang from '../lang';
  import { t } from '@/i18n';
  import avatarImg from '@/assets/images/avatar.png';
  import { storage } from '@/utils/Storage';
  import { accountUpdate } from '@render/api/system/user';
  // import config from '@/config';
  import { useUserStore } from '@/store/modules/user';
  import { useRouter } from 'vue-router';

  const userStore = useUserStore();

  const VUE_APP_BASE_URL = `http://${storage.get('host')}:3000`;

  // const { VUE_APP_BASE_URL } = config;

  const {
    loadLangFn,
    message,
    // language
  } = useMixins();
  loadLangFn(lang);

  const router = useRouter();

  // const route = useRoute();

  // const message = useMessage();

  const loading = ref(false);

  const avatar = ref('');

  // const headers = {
  //   authorization: 'Bearer ' + storage.get('access_token') || '',
  //   'login-id': storage.getCookie('login-id') || '',
  //   language: language.value == 'zh' ? 'zh-cn' : 'en_us',
  //   'tenant-code': storage.getCookie('tenant-code') || '',
  // };

  // 基本信息表单
  const notNull = t('common.formTipMsg.input');
  const basicDataFormSchemas: FormSchema[] = [
    {
      field: 'nickName',
      component: 'NInput',
      label: 'username',
      componentProps: {
        clearable: true,
        maxlength: 32,
        onInput: async () => {
          await handleButtonDisabled();
        },
      },
      rules: [
        {
          required: true,
          message: notNull,
          trigger: ['blur'],
        },
      ],
    },
    {
      field: 'userName',
      component: 'NInput',
      label: 'userAccount',
      componentProps: {
        disabled: true,
        // clearable: true,
      },
    },
    {
      field: 'phone',
      component: 'NInput',
      label: 'phone',
      componentProps: {
        // disabled: true,
        // clearable: true,
        maxlength: 30,
        onInput: async () => {
          await handleButtonDisabled();
        },
      },
      rules: [
        {
          required: true,
          message: notNull,
          trigger: 'blur',
        },
        {
          pattern: /^(\d|\-|\+|\s|\(|\))+$/g,
          message: t('common.formTipMsg.phoneNo'),
          trigger: ['blur', 'input'],
        },
      ],
    },
    {
      field: 'remark',
      component: 'NInput',
      label: 'remark',
      common: true,
      componentProps: {
        // disabled: true,
        // clearable: true,
        type: 'textarea',
        rows: 2,
        maxlength: 100,
        'show-count': true,
        onInput: async () => {
          await handleButtonDisabled();
        },
      },
    },
  ];
  const [
    basicDataFormRegister,
    {
      validate: basicDataValidate,
      getFieldsValue: getBasicDataFormValFn,
      setFieldsValue: setBasicDataFormValFn,
    },
  ] = useForm({
    gridProps: { cols: 1 },
    collapsedRows: 3,
    labelWidth: 120,
    layout: 'horizontal',
    showActionButtonGroup: false,
    schemas: basicDataFormSchemas,
  });
  // 获取用户信息
  interface Props {
    userInfo: any;
  }
  const props = withDefaults(defineProps<Props>(), {
    userInfo: () => {
      return {};
    },
  });

  let userInfo: any = null;

  watch(
    () => props.userInfo,
    (newVal: any) => {
      userInfo = newVal;
      // console.log(newVal);
      avatar.value = userInfo.avatar || '';

      console.log(userInfo);

      nextTick(async () => {
        await setBasicDataFormValFn(userInfo);
      });
    },
    { immediate: true, deep: true }
  );
  // 保存按钮禁用
  const buttonDisabled = ref(true);
  const handleButtonDisabled = async () => {
    const basicDataForm = getBasicDataFormValFn();
    buttonDisabled.value =
      JSON.stringify({
        ...basicDataForm,
        // avatar: avatar.value,
      }) ===
      JSON.stringify({
        ...userInfo,
        id: undefined,
      });
  };
  // const logOut = () => {
  //   userStore.logout().then((res: any) => {
  //     const { message: msg = '', code } = res;
  //     if (code !== 0) {
  //       msg && message.success(msg);
  //     }

  //     router
  //       .replace({
  //         name: 'Login',
  //         query: {
  //           redirect: route.fullPath,
  //         },
  //       })
  //       .finally(() => window.location.reload());
  //   });
  // };

  const $dialog = window['$dialog'];

  // 保存用户信息
  const handleSaveProfileFn = async () => {
    loading.value = true;
    try {
      const isSubmit = await basicDataValidate();
      if (!isSubmit) {
        const basicDataForm = getBasicDataFormValFn();
        const { nickName, phone, remark } = basicDataForm || {};
        const res = await accountUpdate({
          ...cloneDeep(userInfo),
          // avatar: avatar.value,
          nickName,
          phone,
          remark,
          headImg:''
        });
        const { code } = res || {};
        if (code === 200) {
          // const userStore = useUserStoreWidthOut();
          message.success(t('common.tipMsg.saveSuccess'));
          // const { nickName, userName, phoneCode, remark } = row || {};
          // userInfo = { nickName, userName, phoneCode, remark };
          // await userStore.getInfo();
          loading.value = false;
          buttonDisabled.value = true;

          $dialog.warning({
            title: t('common.tipMsg.warning'),
            content: t('common.tipMsg.logoutConfirmMsg2'),
            positiveText: t('common.button.primary'),
            //negativeText: '取消',
            closable: false,
            maskClosable: false,
            onPositiveClick: () => {
              userStore.logout().then(() => {
                router
                  .replace({
                    name: 'Login',
                  })
                  .finally(() => location.reload());
              });
            },
            onNegativeClick: () => {},
          });
          // logOut();
        }
      }
    } catch (e) {
      console.log(e);
      loading.value = false;
    }
  };

  // // 上传头像回调
  // const handleUploadChange = async ({ file }) => {
  //   console.log(file);
  //   const { type, size } = file?.file || {};
  //   if (!type?.includes('image')) {
  //     message.error(t('profile.error.uploadTypeMsg'));
  //     return;
  //   }
  //   if (size && size / 1024 / 1024 > 2) {
  //     message.error(t('profile.error.uploadSizeMsg'));
  //     return;
  //   }
  //   const avatarTemp = await getBase64(file?.file);

  //   console.log(avatarTemp);
  //   avatar.value = avatarTemp as string;
  //   await handleButtonDisabled();
  // };

  //上传完成的回调
  // const handleFinish = (e: any) => {
  //   console.log(e);
  //   try {
  //     const response = JSON.parse(e.event.currentTarget.response);

  //     avatar.value = response.row;

  //     handleButtonDisabled();
  //   } catch (error) {
  //     console.error('失败', error);
  //   }
  // };
  // // 图片转base64
  // const getBase64 = async (file?: any) => {
  //   return new Promise((resolve, reject) => {
  //     const reader = new FileReader();
  //     let fileResult: string | ArrayBuffer | null = null;
  //     reader.readAsDataURL(file);
  //     reader.onload = () => {
  //       fileResult = reader.result;
  //     };
  //     reader.onerror = (error) => {
  //       reject(error);
  //     };
  //     reader.onloadend = () => {
  //       resolve(fileResult);
  //     };
  //   });
  // };
</script>

<style lang="less" scoped>
  .profile {
    &-content {
      &-item {
        width: 500px;
        margin: 0 auto;
        .basicForm {
          margin-bottom: 12px;
          // margin-left: -60px;
          // padding-right: 60px;
        }
      }
      .save-button {
        margin-left: 122px;
        padding: 0 22px;
        height: 32px;
        line-height: 32px;
      }
      .profile-basic-data {
        .avatar {
          text-align: center;
          margin-bottom: 36px;
          .n-avatar {
            margin-bottom: 16px;
            background: transparent;
          }
          .n-button {
            color: @tableButtonColor;
            &:hover {
              color: @tableButtonHoverColor;
            }
          }
        }
      }
    }
  }
</style>
